package publisher.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;


@SuppressWarnings("serial")
public class NewsFeedServlet extends HttpServlet {

	private Logger logger = Logger.getLogger(this.getClass());

	@Override
	public void init(ServletConfig config) throws ServletException {
		logger.debug("init");
		try{
			Class.forName("com.mysql.jdbc.Driver");
		}catch(ClassNotFoundException e){
			throw new ServletException(e);
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		PrintWriter writer = resp.getWriter();
		
		SyndFeed feed = new SyndFeedImpl();
		feed.setFeedType("rss_2.0");
		feed.setTitle("My First News Feed");
		feed.setLink("http://localhost:8080/");
		feed.setDescription("This feed was created using ROME.");
		List<SyndEntry> entries = new Vector<SyndEntry>();
		
		try {
			Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/publisher", "root", "");
			Statement statement = connection.createStatement();
			ResultSet result = statement.executeQuery("SELECT * FROM news_item;");
			while(result.next()){
				String title = result.getString("title");
				String url = result.getString("url");
				java.sql.Date pubDate = result.getDate("pubDate");
				SyndContent content = new SyndContentImpl();
				content.setValue(result.getString("description"));
				SyndEntry entry = new SyndEntryImpl();
				entry.setTitle(title);
				entry.setLink(url);
				entry.setPublishedDate(pubDate);
				entry.setDescription(content);
				entries.add(entry);
			}
			connection.close();
		} catch (SQLException e) {
			logger.error("SQL query failed", e);
		}
		
		resp.setContentType("text/xml");
		feed.setEntries(entries);
		SyndFeedOutput output = new SyndFeedOutput();
		try {
			output.output(feed, writer);
		} catch (FeedException e) {
			logger.error("Feed output failed", e);
		}
	}
	
}
